package com.lora.service.resolver;

import com.lora.dto.EquipmentDto;
import com.lora.entity.AirConditioningUps;
import com.lora.entity.FreshAirUps;
import com.lora.service.FreshAirUpsService;
import com.lora.service.NodeDataResolver;
import com.lora.util.AirConditioningUpsMapping;
import com.lora.util.ClassFormatUtil;
import com.lora.util.FreshAirUpsMapping;
import com.lora.util.StringUtil;
import com.lora.web.BaseUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service("freshAirUpsResolver")
public class FreshAirUpsResolver implements NodeDataResolver<FreshAirUps> {

    @Resource
    private FreshAirUpsService freshAirUpsService;
    @Override
    public EquipmentDto<FreshAirUps> resolve(String equipmentNumber, String data) {
        data = BaseUtil.base64ToHex(data);
        EquipmentDto<FreshAirUps> equipmentDto=new EquipmentDto<>();
        FreshAirUps freshAirUps=new FreshAirUps();
        Map<String,String> map=new HashMap<>();
        data=data.substring(6);
        String machine=equipmentNumber;  //获取设备机号
        freshAirUps.setEquipmentid(equipmentNumber);
        String suffer=data.substring(3,4);  //获取设备功能码
        Integer datalength=Integer.parseInt(data.substring(4,6),16);//获取数据长度
        String crcCode=data.substring(data.length()-4);
        data=data.substring(6,data.length()-4);//去掉前20位和后4位   保留数据长度2位和数据
        for (int i = 1; i <= datalength/2; i++) {
            int address = Integer.parseInt(suffer + (i+11));
            String filed = FreshAirUpsMapping.getFiled(address);
            if (filed == null) continue;
            String sub = data.substring(4 * (i - 1), 4 * i);
            map.put(filed, Integer.parseInt(sub,16) + "");
        }
        if(map!=null&&map.size()>0) {
            ClassFormatUtil.setFiledValue(map, freshAirUps);
            equipmentDto.setEntity(freshAirUps);
        }
        return equipmentDto;
    }

    @Override
    public FreshAirUps save(FreshAirUps equipment, boolean alarmFlag) {
        equipment.setAlarmFlag(alarmFlag);
        freshAirUpsService.save(equipment);
        return equipment;
    }
}
